#include "cwit_notify.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

#define CWIT_NOTIFY_MAP_IS_NULL(notify_map){if(notify_map==NULL) notify_map=&cwit_notify_map;}
typedef struct __cwit_solt{
    void *param;
    void (*notify_calbak)(void *param,void *param1);
}cwit_notify_param;

static cwit_notify cwit_notify_map = {0};

int cwit_notify__recv_calbak(void *front,void *data,void *next,void *param)
{
    cwit_notify_param *solt = data;
    solt->notify_calbak(param,solt->param);
    return 0;
}
/*
    添加通知接收函数
    slotfun： 触发信号后回调函数
    param：信号槽函数传参数
*/
void cwit_notify_recv(cwit_notify *notify_map,void *siganl,int siganl_size, void (*notify_calbak)(void *param,void *param1),void *param)
{
    CWIT_NOTIFY_MAP_IS_NULL(notify_map);
    cwit_list *calbak_list = NULL; 
    if((calbak_list = cwit_map_get_value(notify_map,siganl,siganl_size)) == NULL)
    {
        //创建信号
        calbak_list = malloc(sizeof(cwit_list));
        memset(calbak_list,0,sizeof(cwit_list));
        cwit_map_insert(notify_map,siganl,siganl_size,calbak_list,sizeof(cwit_list));
    }
    cwit_notify_param *notify = malloc(sizeof(cwit_notify_param));
    memset(notify,0,sizeof(cwit_notify_param));
    notify->param = param;
    notify->notify_calbak = notify_calbak;
    cwit_list_push_tail(calbak_list,notify);
}

/*
    发送信号
*/
void cwit_notify_send(cwit_notify *notify_map,void *siganl,int siganl_size,void *data)
{
    CWIT_NOTIFY_MAP_IS_NULL(notify_map);
    cwit_list *calbak_list = NULL; 
    if((calbak_list = cwit_map_get_value(notify_map,siganl,siganl_size)) == NULL)
    {
        return;
    }
    cwit_list_traversal(calbak_list,cwit_notify__recv_calbak,data);
}

static int cwit_notify_remove_condition(void *front,void *data,void *next,void *param)
{
    cwit_notify_param *calbak_list = data; 
    if(calbak_list->notify_calbak == param)
    {
        return 1;
    }
    return 0;
}

void cwit_notify_remove(cwit_notify *notify_map,void *siganl,int siganl_size,void (*notify_calbak)(void *param,void *param1))
{
    CWIT_NOTIFY_MAP_IS_NULL(notify_map);
    cwit_list *calbak_list = NULL; 
    if((calbak_list = cwit_map_get_value(notify_map,siganl,siganl_size)) == NULL)
    {
        return ;
    }
    cwit_list_remove_condition(calbak_list,cwit_notify_remove_condition,notify_calbak);
}

cwit_list* cwit_notify_remove_to_list(cwit_notify *notify_map,void *siganl,int siganl_size,void (*notify_calbak)(void *param,void *param1))
{
    CWIT_NOTIFY_MAP_IS_NULL(notify_map);
    cwit_list *calbak_list = NULL; 
    if((calbak_list = cwit_map_get_value(notify_map,siganl,siganl_size)) == NULL)
    {
        return NULL;
    }
   return cwit_list_remove_condition_to_list(calbak_list,cwit_notify_remove_condition,notify_calbak);
}

int cwit_notify_add_model(char *model)
{
    return 0;
}